package com.tfswx.jkgl.designer;

import cn.hutool.core.net.NetUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpStatus;

import java.nio.charset.StandardCharsets;

/**
 * @author ricky
 * @date 2021/12/5
 */
@Slf4j
@SpringBootApplication
@MapperScan({"com.tfswx.jkgl.designer.dao"})
public class App {
    @Value("${mybatis-plus.configuration.call-setters-on-nulls}")
    private Boolean aBoolean;
    @Value("${spring.profiles.active:}")
    private String active;
    @Getter
    private String appName;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Value("${spring.application.name:}")
    public void setAppName(String appName) {
        if (StringUtils.isEmpty(appName)) {
            this.appName = "未命名项目";
        } else {
            this.appName = new String(appName.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        }
    }

    @EventListener({WebServerInitializedEvent.class})
    public void afterRun(WebServerInitializedEvent event) {
        log.info("setNulls：" + aBoolean);
        String host = NetUtil.getLocalhostStr();
        int port = event.getWebServer().getPort();

        log.info("\n----------------------------------------------------------\n\t" +
                        "程序【{}】已经运行!\n\t" +
                        "环境：\t{}\n\t" +
                        "主页: \thttp://{}:{}\n\t" +
                        "审计: \thttp://{}:{}/actuator\n\t" +
                        //                        "日志: \thttp://{}:{}/log.html\n\t" +
                        "文档: \thttp://{}:{}/doc.html\n" +
                        "----------------------------------------------------------",
                appName, active, host, port, host, port, host, port
                //                , host, port
        );
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return factory -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
            factory.addErrorPages(error404Page);
        };
    }
}
